In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to HTML, all the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.
Photo sharing and photo storage services like to have location data for each photo that is uploaded. With the location data, these services can build advanced features, such as automatic suggestion of relevant tags or automatic photo organization, which help provide a compelling user experience. Although a photo's location can often be obtained by looking at the photo's metadata, many photos uploaded to these services will not have location metadata available. This can happen when, for example, the camera capturing the picture does not have GPS or if a photo's metadata is scrubbed due to privacy concerns.
If no location metadata for an image is available, one way to infer the location is to detect and classify a discernable landmark in the image. Given the large number of landmarks across the world and the immense volume of images that are uploaded to photo sharing services, using human judgement to classify these landmarks would not be feasible.
In this notebook, you will take the first steps towards addressing this problem by building models to automatically predict the location of the image based on any landmarks depicted in the image. At the end of this project, your code will accept any user-supplied image as input and suggest the top k most relevant landmarks from 50 possible landmarks from across the world. The image below displays a potential sample output of your finished project.

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
Note: if you are using the Udacity workspace, YOU CAN SKIP THIS STEP. The dataset can be found in the /data folder and all required Python modules have been installed in the workspace.
Download the landmark dataset.
Unzip the folder and place it in this project's home directory, at the location /landmark_images.
Install the following Python modules:
In this step, you will create a CNN that classifies landmarks. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 20%.
Although 20% may seem low at first glance, it seems more reasonable after realizing how difficult of a problem this is. Many times, an image that is taken at a landmark captures a fairly mundane image of an animal or plant, like in the following picture.

Just by looking at that image alone, would you have been able to guess that it was taken at the Haleakalā National Park in Hawaii?
An accuracy of 20% is significantly better than random guessing, which would provide an accuracy of just 2%. In Step 2 of this notebook, you will have the opportunity to greatly improve accuracy by using transfer learning to create a CNN.
Remember that practice is far ahead of theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
Use the code cell below to create three separate data loaders: one for training data, one for validation data, and one for test data. Randomly split the images located at landmark_images/train to create the train and validation data loaders, and use the images located at landmark_images/test to create the test data loader.
Note: Remember that the dataset can be found at /data/landmark_images/ in the workspace.
All three of your data loaders should be accessible via a dictionary named loaders_scratch. Your train data loader should be at loaders_scratch['train'], your validation data loader should be at loaders_scratch['valid'], and your test data loader should be at loaders_scratch['test'].
You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!
!find /data/landmark_images -maxdepth 4 -type d
import numpy as np
import torch
from torch.utils import data
from torchvision import transforms
from torchvision.datasets import ImageFolder
import torch.nn as nn
import os
!pip install split-folders
import splitfolders
# splitfolders.ratio("/data/landmark_images/train", output="./output", seed=53, ratio=(.8, .2), group_prefix=None) # default values
!ls output
### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
DS_DIR = "/data/landmark_images"
BATCH_SIZE = 2**6
IMG_MEAN = torch.tensor( [0.485, 0.456, 0.406])
IMG_STD = torch.tensor([0.229, 0.224, 0.225])
normalize = transforms.Normalize(mean=IMG_MEAN,
std=IMG_STD)
train_transforms = transforms.Compose([
transforms.Resize(226),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(0.25),
transforms.RandomVerticalFlip(0.25),
transforms.ToTensor(),
normalize
])
test_val_transforms = transforms.Compose([
transforms.Resize(226),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize
])
train_ds = ImageFolder("./output/train", transform=train_transforms)
val_ds = ImageFolder("./output/val", transform=test_val_transforms)
test_ds = ImageFolder(os.path.join(DS_DIR, 'test'), transform=test_val_transforms)
# # Train-Val split
# train_ratio = 0.8
# train_split_idx = int(train_ratio * len(full_ds))
# idxs = np.arange(len(full_ds))
# np.random.shuffle(idxs)
# train_idxs = idxs[:train_split_idx]
# val_idxs = train_idxs = idxs[train_split_idx:]
# train_sampler = data.sampler.SubsetRandomSampler(train_idxs)
# val_sampler = data.sampler.SubsetRandomSampler(val_idxs)
#train_ds, val_ds = data.random_split(full_ds, [train_size, val_size]), not supported in v. 0.4.0 :(
train_loader = data.DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True)
val_loader = data.DataLoader(val_ds, batch_size=BATCH_SIZE, shuffle=False)
test_loader = data.DataLoader(test_ds, batch_size=1, shuffle=False)
loaders_scratch = {'train': train_loader, 'valid': val_loader, 'test': test_loader}
len(train_ds.classes)
len(val_ds.classes)
len(test_ds.classes)
# calculates the Mean and STD of the whole trainning DS
# ds_len = len(train_ds)
# mean, std = 0,0
# for i,y in train_ds:
# mean += i.mean(1).mean(1)
# std += i.std(1).std(1)
# mean /= ds_len
# std /= ds_len
# print([round(n, 5) for n in mean.tolist()])
# print([round(n, 5) for n in std.tolist()])
Question 1: Describe your chosen procedure for preprocessing the data.
Answer:
Use the code cell below to retrieve a batch of images from your train data loader, display at least 5 images simultaneously, and label each displayed image with its class name (e.g., "Golden Gate Bridge").
Visualizing the output of your data loader is a great way to ensure that your data loading and preprocessing are working as expected.
def denormalize_img(x):
x[0, :, :] = x[ 0, :, :] * IMG_STD[0] + IMG_MEAN[0]
x[1, :, :] = x[ 1, :, :] * IMG_STD[1] + IMG_MEAN[1]
x[2, :, :] = x[ 2, :, :] * IMG_STD[2] + IMG_MEAN[2]
return x
import matplotlib.pyplot as plt
%matplotlib inline
idx_to_class = dict(zip(train_ds.class_to_idx.values(), train_ds.class_to_idx.keys()))
## TODO: visualize a batch of the train data loader
fig, axs = plt.subplots(5, 5, figsize=(30, 25))
## the class names can be accessed at the `classes` attribute
## of your dataset object (e.g., `train_dataset.classes`)
temp_ds,y = next(iter(train_loader))
for i, a in enumerate(axs.flatten()):
norm_img = temp_ds[i]
img = denormalize_img(norm_img)
img = img.permute(1, 2, 0)
a.imshow(img.numpy())
a.set_title(f'{idx_to_class[y[i].item()][3: ].replace("_", " ") }')
a.axis('off')
fig.tight_layout()
# useful variable that tells us whether we should use the GPU
use_cuda = torch.cuda.is_available()
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and fill in the function get_optimizer_scratch below.
## TODO: select loss functiondq
criterion_scratch = nn.CrossEntropyLoss()
def get_optimizer_scratch(model):
return torch.optim.Adam(model.parameters(), lr=1e-3)
Create a CNN to classify images of landmarks. Use the template in the code cell below.
import torch.nn as nn
# define the CNN architecture
class Net(nn.Module):
## TODO: choose an architecture, and complete the class
def __init__(self):
super(Net, self).__init__()
## Define layers of a CNN
self.stack = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(2,2),
nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(2,2),
nn.Conv2d(32, 40, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(2,2),
nn.Conv2d(40, 64, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(2,2),
nn.Conv2d(64, 70, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(2,2),
)
self.fc = nn.Sequential(
nn.Linear(7**2 * 70, 4096),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(4096, 50),
)
def forward(self, x):
## Define forward behavior
x = self.stack(x)
x = x.view(-1, 7**2 * 70)
x = self.fc(x)
return x
#-#-# Do NOT modify the code below this line. #-#-#
# instantiate the CNN
model_scratch = Net()
# move tensors to GPU if CUDA is available
if use_cuda:
model_scratch.cuda()
Question 2: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.
Answer: The network is designed to increase the depth while decreasing the feature size to extract patterns at each convolution the depth is increase then the resulting feature map is downsampled by half at each step by a max pool layer.
Implement your training algorithm in the code cell below. Save the final model parameters at the filepath stored in the variable save_path.
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
"""returns trained model"""
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs+1):
# initialize variables to monitor training and validation loss
train_loss = 0.0
valid_loss = 0.0
###################
# train the model #
###################
# set the module to training mode
model.train()
for batch_idx, (data, target) in enumerate(loaders['train']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## TODO: find the loss and update the model parameters accordingly
## record the average training loss, using something like
## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data.item() - train_loss))
out = model(data)
optimizer.zero_grad()
loss = criterion(out, target)
loss.backward()
optimizer.step()
train_loss += loss.item() / len(target)
del data
del target
torch.cuda.empty_cache()
######################
# validate the model #
######################
# set the model to evaluation mode
model.eval()
for batch_idx, (data, target) in enumerate(loaders['valid']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## TODO: update average validation loss
out = model(data)
loss = criterion(out, target)
valid_loss += loss.item() / len(target)
del data
del target
torch.cuda.empty_cache()
# print training/validation statistics
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch,
train_loss,
valid_loss
))
## TODO: if the validation loss has decreased, save the model at the filepath stored in save_path
if (valid_loss < valid_loss_min):
torch.save(model.state_dict(), save_path)
valid_loss_min = valid_loss
print('Model saved!')
return model
Use the code cell below to define a custom weight initialization, and then train with your weight initialization for a few epochs. Make sure that neither the training loss nor validation loss is nan.
Later on, you will be able to see how this compares to training with PyTorch's default weight initialization.
def custom_weight_init(m):
## TODO: implement a weight initialization strategy
if type(m) == nn.Linear:
torch.nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(1e-3)
#-#-# Do NOT modify the code below this line. #-#-#
model_scratch.apply(custom_weight_init)
model_scratch = train(20, loaders_scratch, model_scratch, get_optimizer_scratch(model_scratch),
criterion_scratch, use_cuda, 'ignore.pt')
Run the next code cell to train your model.
## TODO: you may change the number of epochs if you'd like,
## but changing it is not required
num_epochs = 100
#-#-# Do NOT modify the code below this line. #-#-#
# function to re-initialize a model with pytorch's default weight initialization
def default_weight_init(m):
reset_parameters = getattr(m, 'reset_parameters', None)
if callable(reset_parameters):
m.reset_parameters()
# reset the model parameters
model_scratch.apply(default_weight_init)
# train the model
model_scratch = train(num_epochs, loaders_scratch, model_scratch, get_optimizer_scratch(model_scratch),
criterion_scratch, use_cuda, 'model_scratch.pt')
Run the code cell below to try out your model on the test dataset of landmark images. Run the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 20%.
def test(loaders, model, criterion, use_cuda):
# monitor test loss and accuracy
test_loss = 0.
correct = 0.
total = 0.
# set the module to evaluation mode
model.eval()
for batch_idx, (data, target) in enumerate(loaders['test']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update average test loss
test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data.item() - test_loss))
# convert output probabilities to predicted class
pred = output.data.max(1, keepdim=True)[1]
# compare predictions to true label
correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
total += data.size(0)
del data
del target
torch.cuda.empty_cache()
print('Test Loss: {:.6f}\n'.format(test_loss))
print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
100. * correct / total, correct, total))
# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
You will now use transfer learning to create a CNN that can identify landmarks from images. Your CNN must attain at least 60% accuracy on the test set.
Use the code cell below to create three separate data loaders: one for training data, one for validation data, and one for test data. Randomly split the images located at landmark_images/train to create the train and validation data loaders, and use the images located at landmark_images/test to create the test data loader.
All three of your data loaders should be accessible via a dictionary named loaders_transfer. Your train data loader should be at loaders_transfer['train'], your validation data loader should be at loaders_transfer['valid'], and your test data loader should be at loaders_transfer['test'].
If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.
### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
loaders_transfer = loaders_scratch.copy()
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and fill in the function get_optimizer_transfer below.
## TODO: select loss function
criterion_transfer = nn.CrossEntropyLoss()
def get_optimizer_transfer(model):
return torch.optim.Adam(model_transfer.fc.parameters(), lr=1e-3)
Use transfer learning to create a CNN to classify images of landmarks. Use the code cell below, and save your initialized model as the variable model_transfer.
## TODO: Specify model architecture
from torchvision import models
model_transfer = models.resnet18(pretrained=True)
#freeze weights
for param in model_transfer.parameters():
param.requires_grad = False
model_transfer.fc = nn.Linear(model_transfer.fc.in_features, 50)
#-#-# Do NOT modify the code below this line. #-#-#
if use_cuda:
model_transfer = model_transfer.cuda()
model_transfer
Question 3: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer: I selected ResNet18 becaues it migtates the the vanishing gradient issue. Then I only changed the size of the fully connected layer to match the number of our classes. I freezed the weights of the pre-trained ResNet18 and only trained the fully connected layer. Since the model is trained on a larget set of images it suits this problem.
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.
# TODO: train the model and save the best model parameters at filepath 'model_transfer.pt'
num_epochs=100
model_scratch = train(num_epochs, loaders_transfer, model_transfer, get_optimizer_transfer(model_transfer),
criterion_transfer, use_cuda, 'model_transfer.pt')
#-#-# Do NOT modify the code below this line. #-#-#
# load the model that got the best validation accuracy
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
Try out your model on the test dataset of landmark images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
Great job creating your CNN models! Now that you have put in all the hard work of creating accurate classifiers, let's define some functions to make it easy for others to use your classifiers.
Implement the function predict_landmarks, which accepts a file path to an image and an integer k, and then predicts the top k most likely landmarks. You are required to use your transfer learned CNN from Step 2 to predict the landmarks.
An example of the expected behavior of predict_landmarks:
>>> predicted_landmarks = predict_landmarks('example_image.jpg', 3)
>>> print(predicted_landmarks)
['Golden Gate Bridge', 'Brooklyn Bridge', 'Sydney Harbour Bridge']
test_transforms = transforms.Compose([
transforms.Resize(226),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize
])
import cv2
from PIL import Image
## the class names can be accessed at the `classes` attribute
## of your dataset object (e.g., `train_dataset.classes`)
def predict_landmarks(img_path, k):
## TODO: return the names of the top k landmarks predicted by the transfer learned CNN
model_transfer.eval()
img = Image.open(img_path)
img = test_transforms(img).unsqueeze(0).cuda()
out = model_transfer(img)
del img
idxs = torch.topk(out, k)[1][0].tolist()
classes = list(train_ds.class_to_idx.keys())
return [''.join(s for s in classes[i].replace('_', ' ') if s.isalpha() or s == ' ') for i in idxs]
# test on a sample image
predict_landmarks('images/test/09.Golden_Gate_Bridge/190f3bae17c32c37.jpg', 5)
In the code cell below, implement the function suggest_locations, which accepts a file path to an image as input, and then displays the image and the top 3 most likely landmarks as predicted by predict_landmarks.
Some sample output for suggest_locations is provided below, but feel free to design your own user experience!

def suggest_locations(img_path):
# get landmark predictions
predicted_landmarks = predict_landmarks(img_path, 3)
text = ', '.join(predicted_landmarks[:-1]) + ' or ' + predicted_landmarks[-1]
## TODO: display image and display landmark predictions
fig, ax = plt.subplots()
img = Image.open(img_path)
ax.imshow(img)
ax.set_xlabel(f'Is this picture for the\n {text}?')
# test on a sample image
suggest_locations('images/test/09.Golden_Gate_Bridge/190f3bae17c32c37.jpg')
Test your algorithm by running the suggest_locations function on at least four images on your computer. Feel free to use any images you like.
Question 4: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
!wget https://www.nyc.gov/html/dot/images/infrastructure/brooklyn-bridge.jpg
!wget https://www.detail-online.com/fileadmin/uploads/olympic_Nachtteaser1_Olympic_Stadium_CGI_01.jpg
Answer: (Three possible points for improvement)
suggest_locations('./brooklyn-bridge.jpg')
suggest_locations('./olympic_Nachtteaser1_Olympic_Stadium_CGI_01.jpg')
!wget https://image.freepik.com/photos-gratuite/forth-bridge-edinburgh_63253-7067.jpg
suggest_locations('./forth-bridge-edinburgh_63253-7067.jpg')
!wget https://upload.wikimedia.org/wikipedia/commons/9/93/Rathaus_Vienna_June_2006_165.jpg
suggest_locations('./Rathaus_Vienna_June_2006_165.jpg')
!wget https://upload.wikimedia.org/wikipedia/commons/d/d3/Gateway_of_India_-Mumbai.jpg
suggest_locations('./Gateway_of_India_-Mumbai.jpg')